package pers.zifeng.distributed.lock.mysql.event;

import lombok.extern.slf4j.Slf4j;
import pers.zifeng.distributed.lock.mysql.service.MysqlDistributedLockService;

import java.lang.management.ManagementFactory;

/**
 * @author: zf
 * @date: 2021/05/14 17:21:06
 * @version: 1.0.0
 * @description: mysql分布式锁-锁表
 * 执行流程: 多进程抢占数据库中某个资源然后执行业务，执行完毕释放资源
 * 锁机制: 单一进程获取锁时则其他进程提交失败
 */
@Slf4j
public class LockTable extends Thread {
    @Override
    public void run() {
        super.run();
        String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
        try {
            while (true) {
                log.info("当前线程:" + pid + ",尝试获取锁资源！");
                if (MysqlDistributedLockService.tryLock(1, "测试锁")) {
                    log.info("当前线程:" + pid + ",获取锁资源成功！");
                    // 这里用sleep模拟业务处理过程
                    log.info("开始处理业务！");
                    Thread.sleep(10 * 1000);
                    log.info("业务处理完成！");
                    MysqlDistributedLockService.releaseLock(1);
                    log.info("当前线程:" + pid + "，释放了锁资源！");
                    break;
                } else {
                    log.info("当前线程:" + pid + ",获取锁资源失败！");
                    Thread.sleep(2000);
                }
            }
        } catch (Exception e) {
            log.error("抢占锁发生错误！", e);
        } finally {
            MysqlDistributedLockService.close();
        }

    }

    // 程序入口
    public static void main(String[] args) {
        new LockTable().start();
    }

}
